package org.wangle.seckill.auth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class CustomAuthExceptionHandler implements AuthenticationEntryPoint, AccessDeniedHandler {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        //获取AuthenticationException错误
        Throwable cause = authException.getCause();
        JSONObject jsonObject = new JSONObject();
        //定义返回的
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");
        if(cause instanceof AuthenticationCredentialsNotFoundException) {
            log.error("InsufficientAuthenticationException : {}", cause.getMessage());
            jsonObject.put("message","Token允许访问的资源不匹配");
            jsonObject.put("code",1);
            response.getWriter().write(jsonObject.toJSONString());

        }

        if (cause instanceof InvalidTokenException) {

            String token = request.getHeader(HttpHeaders.AUTHORIZATION);

            log.error("InvalidTokenException : {}", cause.getMessage());
            jsonObject.put("message","token无效");
            jsonObject.put("code",1);
            // Token无效
            response.getWriter().write(jsonObject.toJSONString());
        } else {
            log.error("AuthenticationException : NoAuthentication");
            jsonObject.put("message","资源未授权");
            jsonObject.put("code",1);
            // Token无效
            response.getWriter().write(jsonObject.toJSONString());
        }

    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.addHeader("Access-Control-Max-Age", "1800");
        // 访问资源的用户权限不足
        log.error("AccessDeniedException : {}", accessDeniedException.getMessage());
        response.getWriter().write(JSON.toJSONString("访问资源的用户权限不足"));
    }
}